﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using System.Data.SQLite;
using System.Data;

using System.Reflection;

using HtmlAgilityPack;
using System.Diagnostics;
using System.Collections;

namespace DataFinder
{
    class Program
    {
        static Dictionary<int, string> shiplist;
        static List<shipdata> ships;
        static void Main(string[] args)
        {
            shiplist = LoadShipData();
            ships = new List<shipdata>();
            //var hd = LoadShipFromID(1);
            GetFromHardDisk();
            //hd.ToString();
            //var dt = ToDataTable(ships[0].OriginalJson);
            //LoadShip(1);
            SetDB();
            //var sql = string.Format("insert into ships {0}", hd.ToSQLValue());

            Console.ReadLine();
        }
        static void SetDB()
        {
            Dictionary<int, string> shiplist = LoadShipData();

            string connectString = string.Format(@"Data Source={0};Pooling=true;FailIfMissing=false",Path.Combine(System.Windows.Forms.Application.StartupPath,"database.db"));
            SQLiteConnection conn = new SQLiteConnection(connectString);
            conn.Open();

            string sqlformat = "insert into shiplist values('{0}','{1}')";
            string sql="";
            SQLiteCommand cmd;
            foreach (KeyValuePair<int, string> t in shiplist)
            {
                sql = string.Format(sqlformat, t.Key, t.Value);
                cmd = new SQLiteCommand(sql, conn);
                cmd.CommandType = CommandType.Text;
                Console.WriteLine(sql);
                cmd.ExecuteNonQuery();
            }

            sqlformat = "insert into ships {0}";
            sql = "";
            foreach (shipdata sp in ships)
            {
                sql = string.Format(sqlformat, sp.ToSQLValue());
                cmd = new SQLiteCommand(sql, conn);
                cmd.CommandType = CommandType.Text;
                Console.WriteLine(sql);
                cmd.ExecuteNonQuery();
            }

        }

        static void GetFromHardDisk()
        {
            FileStream fs;
            StreamReader sr;
            string s = "";

            foreach (KeyValuePair<int, string> t in shiplist)
            {
                try
                {
                    fs = new FileStream(Path.Combine(System.Windows.Forms.Application.StartupPath, "Data", string.Format("{0}.txt", t.Key)), FileMode.Open);
                    sr = new StreamReader(fs);
                    //s = staticPost(@"http://js.ntwikis.com/rest/cancollezh/charactordetail", string.Format("detailid={0}", t.Key));
                    s = sr.ReadToEnd();
                    ships.Add(LoadShip(s));
                    sr.Close();
                    fs.Close();
                }
                catch (Exception)
                {
                    Console.WriteLine(string.Format("Error: {0},{1}", t.Key, t.Value));
                }

            }
        }

        static void GetFromInternet()
        {
            Dictionary<int, string> shiplist = LoadShipData();
            //List<shipdata> ships = new List<shipdata>();

            FileStream fs;
            StreamWriter sw;
            string s = "";

            foreach (KeyValuePair<int, string> t in shiplist)
            {
                Console.WriteLine(t.Key.ToString());
                fs = new FileStream(Path.Combine(System.Windows.Forms.Application.StartupPath, "Data", string.Format("{0}.txt", t.Key)), FileMode.OpenOrCreate);
                sw = new StreamWriter(fs);
                s = staticPost(@"http://js.ntwikis.com/rest/cancollezh/charactordetail", string.Format("detailid={0}", t.Key));
                sw.Write(s);
                sw.Flush();
                sw.Close();
                fs.Close();
            }
            //string s = staticPost(@"http://js.ntwikis.com/rest/cancollezh/charactordetail", @"detailid=1"); ID换掉
            //string s = staticPost(@"http://js.ntwikis.com/rest/cancollezh/charactorquery","");
            //string s = staticPost(@"http://js.ntwikis.com/rest/cancollezh/weaponsquery","");
            //没什么用 Console里面一样抽风 待修复 string s = staticPost(@"http://js.ntwikis.com/rest/cancollezh/weaponsdetail", @"detailname=J国12厘米单装炮");

            //LoadShip(1018);
            Console.ReadLine();
        }

        static void LoadShip(int id)
        {
            JsonSerializer serializer = new JsonSerializer();

            string s = staticPost(@"http://js.ntwikis.com/rest/cancollezh/charactordetail", string.Format("detailid={0}",id));
            //string s = "{\"wedding_talk\": \"约定好了哦，这场战争结束以后就一起回英国。享受蓝天，海风，恬静的下午茶。\"}";
            JsonReader reader = new JsonTextReader(new StringReader(s));
            //shipdata s1 = (shipdata)serializer.Deserialize(reader, typeof(shipdata));
            //Console.WriteLine(s1.WEDDING_TALK);
            reader.Read();
            bool flag = true;
            string varname = "";
            string vartype = "";
            while (flag)
            {
                flag = reader.Read();
                if (reader.TokenType.ToString() == "EndObject") reader.Read();
                if (reader.Value != null)
                    varname = reader.Value.ToString();
                flag = reader.Read();
                if (reader.TokenType != null)
                    vartype = reader.TokenType.ToString();

                Debug.Print(string.Format("{0} {1},", varname, vartype));
                //Debug.Print(reader.TokenType + "\t\t" + reader.ValueType + "\t\t" + reader.Value);
            }
            
            //var hd = Deserializer<shipdata>.JsonDeserializeSingleData(s);
        }
        static shipdata LoadShip(string json)
        {
            JsonSerializer serializer = new JsonSerializer();
            JsonReader reader = new JsonTextReader(new StringReader(json));
            shipdata s1 = (shipdata)serializer.Deserialize(reader, typeof(shipdata));
            return s1;
        }

        static shipdata LoadShipFromID(int id)
        {
            string s = staticPost(@"http://js.ntwikis.com/rest/cancollezh/charactordetail", string.Format("detailid={0}", id));
            return LoadShip(s);
        }


        static Dictionary<int, string> LoadShipData()
        {
            Dictionary<int, string> shiplist = new Dictionary<int, string>();
            string s = staticPost(@"http://js.ntwikis.com/rest/cancollezh/charactorquery", "");

            HtmlDocument hdoc = new HtmlDocument();
            hdoc.LoadHtml(s);
            string pattern = @"(?<=').*?(?=')";

            foreach (HtmlNode nd in hdoc.DocumentNode.ChildNodes)
            {
                string res = nd.ChildNodes[1].Attributes[1].Value;
                MatchCollection matches = Regex.Matches(res, pattern);
                shiplist.Add(int.Parse(matches[0].ToString()), matches[2].ToString());
            }
            return shiplist;
        }
        private static string staticPost(string url, string param)
        {
            try
            {
                byte[] bs = Encoding.UTF8.GetBytes(param);
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                req.Timeout = 10000;
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = bs.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                }
                HttpWebResponse httpWebResponse = (HttpWebResponse)req.GetResponse();
                Stream stream = httpWebResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
                string result = streamReader.ReadToEnd();
                stream.Close();
                return result;
            }
            catch (Exception e)
            {
                throw e;
            }

        }
    }
}
